package com.cloud.security.core.service;

import com.cloud.admin.beans.dto.UserDTO;
import com.cloud.admin.feign.IUserService;
import com.cloud.common.base.Result;
import com.cloud.security.core.security.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 默认的 UserDetailsService 实现
 * 不做任何处理，只在控制台打印一句日志，然后抛出异常，提醒业务系统自己配置 UserDetailsService。
 * @author Aijm
 * @since 2019/5/27
 */
@Slf4j
@Component
public class DefaultUserDetailsServiceImpl implements ProUserDetailsService {

	@Autowired
	private IUserService userService;

	@Autowired
	private BCryptPasswordEncoder passwordEncoder;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		Result<UserDTO> user = userService.info(username);
		log.info("123456 查到的信息密码加密:" +  passwordEncoder.encode("123456"));
		Set<String> dbAuthsSet = new HashSet<>();
		dbAuthsSet.add("sys");
		Collection<? extends GrantedAuthority> authorities
				= AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
		return new SecurityUser(username, user.getData().getPassword(), authorities, user.getData().getTenantId());
	}

	@Override
	public UserDetails loadUserByMoblie(String mobile) throws UsernameNotFoundException {

		long l = System.currentTimeMillis();
		log.warn("请配置 UserDetailsService 接口的实现.");
		Result<UserDTO> user = userService.infoByMobile(mobile);
		log.info("user 查到的信息:" + user.toString());
		long end = System.currentTimeMillis();
		log.info("feign 远程调用时间为:{}s", (end-l)/1000L);
		Set<String> dbAuthsSet = new HashSet<>();
		dbAuthsSet.add("sys");

		Collection<? extends GrantedAuthority> authorities
				= AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
		return new User(mobile, passwordEncoder.encode(mobile),authorities);
	}
}
